'use strict';

import React from 'react';
import {
    View,
    Text,
    StyleSheet,
    FlatList,
    Dimensions
} from 'react-native';

/**
 * 初步开始
 */
export default class List extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            refreshing: false,
            loadText: "",
            list: [],
        }
        this.pageIndex = -1;
        this.loading = false;
    }

    render() {
        return <FlatList ref="flatlist"
            data={this.state.list}
            style={{ flex: 1, backgroundColor: "#f2f2f2" }}
            refreshing={this.state.refreshing}
            numColumns={1}
            onRefresh={() => this.refresh()}
            onEndReached={() => this.next()}
            renderItem={({ item, index }) => this.renderItem(item, index)}
            extraData={this.state}
            keyExtractor={item => item.index}
            scrollEventThrottle={100}
            initialNumToRender={2}
            ListHeaderComponent={this.header()}
            ListEmptyComponent={this.empty()}
            ListFooterComponent={this.footer()}
        />
    }

    componentWillMount() {
        this.next();
    }

    refresh() {
        this.pageIndex = -1;
        this.loading = false;
        this.setState({ list: [] });
        this.next();
    }

    async next() {
        if (this.loading) return;
        this.loading = true;
        this.pageIndex++;
        this.setState({ loadText: "加载中..." })
        let data = await this.load(this.pageIndex);
        if (!data || data.items.length == 0) {
            if (this.state.list.length > this.minCount) this.setState({ loadText: "已经到底了" });
            if (this.state.list.length <= this.minCount) this.setState({ loadText: "" });
            return;
        }
        data.items.forEach((item, index) => {
            item.index = item.sku + this.pageIndex;
            item.show = false;
        });
        this.setState({ list: this.state.list.concat(data.items) });
        this.loading = false;
        if (this.pageIndex == 0) this.showImage(0);
    }

    header() {
        return null;
    }
    footer() {
        return <View style={listStyle.loading}>
            <Text>{this.state.loadText}</Text>
        </View>;
    }
    empty() {
        return <View style={listStyle.empty}>
            <Text style={listStyle.emptyTxt}>暂无该项</Text>
        </View>;
    }
    renderItem(item, index) {
        return null;
    }
    /**
     * 可继承,加载数据
     */
    async load() { }

}